package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.service.reward_points.RewradPointsService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.apache.rocketmq.spring.support.RocketMQConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@RocketMQMessageListener(topic = "countAndOrder",consumerGroup = "my-order")
public class RewardPoints implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {
    @Value("${order.key}")
    String key;
    @Reference
    private RewradPointsService rewradPointsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void onMessage(String orderParent) {

    }


    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext context) {
                MessageExt msg = list.get(0);
                try {
                    String msgbody = new String(msg.getBody(), "utf-8");
                    rewradPointsService.updateReward(msgbody);
                } catch (Exception e) {
                    e.printStackTrace();
                    String msgId = msg.getMsgId();
                    int times = msg.getReconsumeTimes();
                    if (times == 2){
                        redisTemplate.opsForHash().put(key,msgId,msg);
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }else {
                        // 该条消息可以存储到DB或者LOG日志中，或其他处理方式，然后重试
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;// 重试
                    }

                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
    }
}

